//
//  AppDelegate.m
//  JYHospital
//
//  Created by 胡金东 on 16/3/31.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "AppDelegate.h"

#import "HJDRootTool.h"
#import "HJDLoginViewController.h"
#import "HJDNewFeatureController.h"
#import "HJDPesonalCenterViewController.h"
#import "HJDTabBarController.h"
#import "RESideMenu.h"
#import "Reachability.h"
//极光推送
#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#import "HJDPapreViewController.h"
#import "HJDFileViewController.h"
//微信分享
#import "WXApi.h"

#import "BSMacros.h"



////版本号
//#define HJDVersionKey @"version"


@interface AppDelegate ()<RESideMenuDelegate,WXApiDelegate>

@property (nonatomic,strong) UILabel *lbl;
@property (nonatomic, strong) Reachability *reach;



@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 监听网络状态改变的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    
    // 创建Reachability
    self.reach = [Reachability reachabilityForInternetConnection];
    // 开始监控网络(一旦网络状态发生改变, 就会发出通知kReachabilityChangedNotification)
    [self.reach startNotifier];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    
    //    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    
    
    


    //1.获取当前的版本号
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];
    //2.获取上一次的版本号
//    NSString *lastVersion = [[NSUserDefaults standardUserDefaults]objectForKey:HJDVersionKey];
   
//    判断是不是第一次启动应用
      if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])

          {
    
                   //如果是第一次启动的话,使用HJDNewFeatureController (用户引导页面) 作为根视图
              HJDNewFeatureController *NFColl = [[HJDNewFeatureController alloc]init];
              self.window.rootViewController = NFColl;
              [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
              //        保存当前的版本，用偏好设置
              [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:HJDVersionKey];

        }else{
                    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                
                    NSString * phonte = [defaults objectForKey:@"uId"];


                if (phonte == nil) {
                    
                    HJDLoginViewController *login = [[HJDLoginViewController alloc]init];
                    
                    self.window.rootViewController = login;

                    
                }else{

                        HJDTabBarController *tabBar = [[HJDTabBarController alloc]init];
                        HJDPesonalCenterViewController *personalVC = [[HJDPesonalCenterViewController alloc] init];
                        
                        RESideMenu *sideMenuViewController = [[RESideMenu alloc]initWithContentViewController: tabBar leftMenuViewController:personalVC  rightMenuViewController:nil];
                        
                        sideMenuViewController.backgroundImage = [UIImage imageNamed:@"bg"];
                        sideMenuViewController.menuPreferredStatusBarStyle = 1; // UIStatusBarStyleLightContent
                        sideMenuViewController.delegate = self;
                        sideMenuViewController.contentViewShadowColor = [UIColor blackColor];
                        sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
                        sideMenuViewController.contentViewShadowOpacity = 0.2;
                        sideMenuViewController.contentViewShadowRadius = 12;
                        sideMenuViewController.contentViewShadowEnabled = YES;
                        
                        // 切换根控制器:可以直接把之前的根控制器清空
                        
                        self.window.rootViewController = sideMenuViewController;
                    
            }
        }

         
    [self.window makeKeyAndVisible];
    
    NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
    NSString *str = [defa objectForKey:@"tian"];
    UIImageView *niceView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    niceView.image = [UIImage imageNamed:@"Default"];
  
    if (str == nil) {
        CGFloat lblW = IS_IPHONE_5?320:IS_IPHONE_6?375:IS_IPHONE_6_PLUS?414:320;
           self.lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, lblW, 100)];
        self.lbl.text = @"宝宝，触摸着你的心跳，我很幸福";
        self.lbl.textAlignment = NSTextAlignmentCenter;
        self.lbl.font = [UIFont fontWithName:@"2.0-" size:20];
        self.lbl.textColor = [UIColor getColorWithHexNumber:@"FF6087"];
        [niceView addSubview:self.lbl];
    }else{
    CGFloat lblW = IS_IPHONE_5?320:IS_IPHONE_6?375:IS_IPHONE_6_PLUS?414:320;
      self.lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, lblW, 100)];
        if ([str integerValue]<=0) {
            str = @"0";
            self.lbl.text = [NSString stringWithFormat:@"距离宝宝出生倒计时\n%@天",str];
            self.lbl.textAlignment = NSTextAlignmentCenter;
            self.lbl.numberOfLines = 0;

        }
            self.lbl.font = [UIFont fontWithName:@"2.0-" size:30];
    self.lbl.textColor = [UIColor getColorWithHexNumber:@"FF6087"];
    [niceView addSubview:self.lbl];
    }
    
    //添加到场景
    [self.window addSubview:niceView];
    
    //放到最顶层;
    [self.window bringSubviewToFront:niceView];
    
    


    
    //开始设置动画;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:3.0];
    [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.window cache:YES];
//    [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight forView:self.window cache:YES];
    [UIView setAnimationDelegate:self];
   
    niceView.alpha = 0.0;
    niceView.frame = CGRectMake(0, 0, HJDWidth, HJDHeight);
    [UIView commitAnimations];
    
//    [self VersionButton];

    [WXApi registerApp:@"wxde0d43c865c41e1c"];
                return YES;
                

                
}

//微信回调
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}
//微信回调
//- (void)onResp:(BaseResp *)resp {
//    
//    //把返回的类型转换成与发送时相对于的返回类型,这里为SendMessageToWXResp
//    SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
////    if (<#condition#>) {
////        <#statements#>
////    }
//    
//    
//    //使用UIAlertView 显示回调信息
//    NSString *str = [NSString stringWithFormat:@"%d",sendResp.errCode];
//    
//    
//    
//    
//    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"回调信息" message:str delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//    [alertview show];
//}

//-(void)VersionButton
//{
////    获取发布版本的Version
//    NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/cn/lookup?id=1136954921"] usedEncoding:NSUTF8StringEncoding error:nil];
//    if (string !=nil &&[string length]>0 && [string rangeOfString:@"version"].length == 7) {
//        [self checkAppUpdate:string];
//    }
//}

//-(void)checkAppUpdate:(NSString *)appInfo{
//    //1.获取当前的版本号
//    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];
//    NSString *app = [appInfo substringFromIndex:[appInfo rangeOfString:@"\"version\":"].location+10];
//    app = [[app substringToIndex:[app rangeOfString:@","].location]stringByReplacingOccurrencesOfString:@"\"" withString:@""];
//    if (![app isEqualToString:currentVersion]) {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:[NSString stringWithFormat:@"新版本%@已发布",app] delegate:self.class cancelButtonTitle:@"知道了" otherButtonTitles: nil];
//        alert.delegate = self;
//        [alert addButtonWithTitle:@"前往更新"];
//        [alert show];
//        alert.tag = 20;
//    }
//}


//-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
//{
//    if (buttonIndex  ==1 & alertView.tag == 20) {
//        NSString *url = @"";
//        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
//    }
//}

- (void)networkDidLogin:(NSNotification *)notification {
    
    
    if ([JPUSHService registrationID]) {
        NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
        [defa setObject:[JPUSHService registrationID] forKey:@"RegistrationID"];
    }
}



// 处理网络状态改变
- (void)networkStateChange
{
    // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    // 2.检测手机是否能上网络(WIFI\3G\2.5G)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
      
    } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
        
    } else { // 没有网络

          //初始化提示框；
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有网络，请设置网络" preferredStyle:  UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //点击按钮的响应事件；
        }]];
        
        //弹出提示框；
        [self.window.rootViewController presentViewController:alert animated:true completion:nil];
   
    }
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSDictionary *infoDicS = (NSDictionary *)userInfo;
    NSString *successfolStr = infoDicS[@"type"];
    if ([successfolStr integerValue]==1) {
        HJDFileViewController *file = [[HJDFileViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:file];
        [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
    }
    if ([successfolStr integerValue]==2) {
        
        HJDPapreViewController *time = [[HJDPapreViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:time];
        [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
    }

    
    

    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    badge --;
     [JPUSHService setBadge:badge];
    
    //    小红点清零
        application.applicationIconBadgeNumber --;
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"推送的消息%@",userInfo);
    
    NSDictionary *infoDicS = (NSDictionary *)userInfo;
    NSString *successfolStr = infoDicS[@"type"];
    if ([successfolStr integerValue]==1) {
        HJDFileViewController *file = [[HJDFileViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:file];
        [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
    }
    if ([successfolStr integerValue]==2) {
        
        HJDPapreViewController *time = [[HJDPapreViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:time];
        [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
    }

    
    
    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    badge --;
    
    [JPUSHService setBadge:badge];
    //    小红点清零
    application.applicationIconBadgeNumber --;
    
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}




- (void)applicationWillResignActive:(UIApplication *)application {
    
    NSLog(@"进入前台");
    [JPUSHService setBadge:0];//重置JPush服务器上面的badge值。如果下次服务端推送badge传"+1",则会在你当时JPush服务器上该设备的badge值的基础上＋1；
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];//apple自己的接口，变更应用本地（icon）的badge值；

   
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
   }

- (void)applicationWillEnterForeground:(UIApplication *)application {
   
//    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
//    [application setApplicationIconBadgeNumber:0];
//    [application cancelAllLocalNotifications];
//   
//
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
